package com.shenhangye.pushlive.filter

import android.content.Context
import android.opengl.GLES30
import com.shenhangye.pushlive.util.OpenGLUtils

open class FboBaseFilter(context: Context, verid: Int, fragId: Int) :
    BaseFilter(context, verid, fragId) {
    var mFrameBuffers:IntArray?=IntArray(1)
    var mFrameBufferTextures:IntArray?=IntArray(1)

    private fun destroyFrameBuffers(){
        //删除fbo的纹理
        if (mFrameBufferTextures != null) {
            GLES30.glDeleteTextures(1, mFrameBufferTextures, 0)
            mFrameBufferTextures = null
        }

        //删除fbo
        if (mFrameBuffers != null) {
            GLES30.glDeleteFramebuffers(1, mFrameBuffers, 0)
            mFrameBuffers = null
        }
    }

    override fun setSize(width: Int, height: Int) {
        super.setSize(width, height)

        if (mFrameBuffers != null) {
            destroyFrameBuffers()
        }
        mFrameBuffers=IntArray(1)
        mFrameBuffers?.size?.let { GLES30.glGenFramebuffers(it,mFrameBuffers,0) }
        mFrameBufferTextures=IntArray(1)


        //创建纹理
        OpenGLUtils.glGenTextures(mFrameBufferTextures,GLES30.GL_TEXTURE_2D)

        //让fbo与 纹理发生关系
        //创建一个 2d的图像
        // 目标 2d纹理+等级 + 格式 +宽、高+ 格式 + 数据类型(byte) + 像素数据
        GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, mFrameBufferTextures!![0])
        GLES30.glTexImage2D(
            GLES30.GL_TEXTURE_2D, 0, GLES30.GL_RGBA, mWidth, mHeight,
            0, GLES30.GL_RGBA, GLES30.GL_UNSIGNED_BYTE, null
        )

        // 让fbo与纹理绑定起来 ， 后续的操作就是在操作fbo与这个纹理上了
        GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, mFrameBuffers!![0])
        GLES30.glFramebufferTexture2D(
            GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0,
            GLES30.GL_TEXTURE_2D, mFrameBufferTextures!![0], 0
        )

        //解绑
        GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0)
        GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)

    }

    override fun onDraw(texture: Int): Int {
        GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, mFrameBuffers!![0])
        super.onDraw(texture)
        GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
        return mFrameBufferTextures!![0]
    }



}